package com.lfd.rocketmq.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.rocketmq.service
 * @文件名: AsyncRockMQ
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/9/30 22:11
 * @描述：11.1异步消息生产者
 */
@Slf4j
@Service
public class AsyncProducerRockMQ {
    @Autowired
    private ObjectMapper objectMapper;

    public void sendAsyncMsg(String namesrvAddr, String topic, String tag, String msg) throws MQClientException, MQBrokerException, RemotingException, InterruptedException, IOException {
        // 创建生产者并指定生产者组
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer(topic);
        defaultMQProducer.setNamesrvAddr(namesrvAddr);
        defaultMQProducer.start();
        for (int i = 0; i < 10; i++) {
            Message message = new Message(topic, tag, msg.getBytes());
            log.info("线程名:{}", Thread.currentThread().getName());//主线程
            defaultMQProducer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    String json = null;
                    try {
                        json = objectMapper.writeValueAsString(sendResult);
                        log.info("AsyncRockMQ onSuccess,json:{}", json);
                        //NettyClientPublicExecutor_1 NettyClientPublicExecutor_4 NettyClientPublicExecutor_16
                        log.info("send线程名:{}", Thread.currentThread().getName());

                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void onException(Throwable e) {
                    log.info("AsyncRockMQ onException,Throwable:{}", e.getMessage());
                    e.printStackTrace();
                }
            });
        }
        // 挂起jvm 因为回调是异步的不然测试不出来
//        System.in.read();
        // 关闭实例
//        defaultMQProducer.shutdown();
    }
}
